<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>分页查询示例</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f9;
        }
        .container {
            width: 80%;
            margin: 50px auto;
            background: #fff;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            padding: 20px;
            border-radius: 8px;
        }
        .property {
            border-bottom: 1px solid #ddd;
            padding: 15px 0;
            display: flex;
        }
        .property:last-child {
            border-bottom: none;
        }
        .property img {
            width: 200px;
            height: 150px;
            object-fit: cover;
            border-radius: 8px;
            margin-right: 20px;
        }
        .property h3 {
            margin: 0;
            color: #333;
        }
        .property p {
            margin: 5px 0;
            color: #666;
        }
        .pagination {
            display: flex;
            justify-content: center;
            margin-top: 20px;
        }
        .pagination button {
            background: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            margin: 0 5px;
            border-radius: 4px;
            cursor: pointer;
        }
        .pagination button:disabled {
            background: #ccc;
            cursor: not-allowed;
        }
        .sort-options {
            display: flex;
            border-bottom: 2px solid green;
            height:60px;
            margin-top: 20px;

        }
        .sort-options button {
            flex: 1;
            padding: 10px;
            border: none;
            background: none;
            cursor: pointer;
            font-size: 20px;
        }
        .sort-options button.active {
            color: white;
            background-color: #00ae66;
        }
        .sort-options button:not(.active):hover {
            background-color: lightgray;
        }
        .caption {
            font-weight: bold;
            color: #007bff;
            font-size: 30px;
        }
        .caption:hover {
            color: #0056b3;
            cursor: pointer;
        }
        .price {
            color: red;
            font-size: 30px;
            font-weight: bold;
            position: relative;
            right: -700px;
            bottom: 65px;
        }
        .search-form {
            display: flex;
            flex-wrap: wrap;
            background: white;
            /*padding: 20px;*/
            border-radius: 10px;
            /*box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);*/
            width:100%;
            margin: 0 auto;
        }
        .search-form label {
            width: 100px;
            font-weight: bold;
            color: #333;
            margin-right: 10px;
            line-height: 32px;
        }
        .search-form input, .search-form select {
            flex: 1;
            padding: 8px;
            margin-bottom: 15px;
            border: 1px solid #ccc;
            border-radius: 5px;
            font-size: 16px;
        }
        .search-form button {
            /*width: 100%;*/
            padding: 10px;
            background: #007BFF;
            border: none;
            border-radius: 5px;
            color: white;
            font-size: 16px;
            cursor: pointer;
            transition: background 0.3s ease;
        }
        .search-form button:hover {
            background: #0056b3;
        }
        .form-group {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
            flex-basis: 50%; /* Adjust this to control the width */
        }
    </style>

</head>
<body>
<div style="text-align: center;position:relative;top:30px;font-size:40px;font-weight:bold">新房资源</div>
<div class="container">
    <div class="search-form">
        <label style="position: relative;left: 20px" for="title">标题:</label>
        <input style="position: relative;left: -40px" type="text" id="title" name="title">

        <label for="province">省份:</label>
        <select style="position: relative;left: -60px" id="province" name="province">
            <option value="">全部</option>
            <option value="广东省">广东省</option>
            <option value="北京市">北京市</option>
            <option value="上海市">上海市</option>
            <option value="浙江省">浙江省</option>
            <option value="江苏省">江苏省</option>
            <option value="湖南省">湖南省</option>
            <option value="海南省">海南省</option>
            <option value="四川省">四川省</option>
            <option value="陕西省">陕西省</option>
            <option value="福建省">福建省</option>
            <option value="湖北省">湖北省</option>
            <option value="云南省">云南省</option>
            <option value="河南省">河南省</option>
            <option value="山东省">浙江省</option>
            <option value="湖北省">浙江省</option>
            <option value="重庆市">重庆市</option>
        </select>

        <label for="city">城市:</label>
        <select  style="position: relative;left: -60px" id="city" name="city">
            <option value="">全部</option>
            <option value="深圳市">深圳市</option>
            <option value="湛江市">湛江市</option>
            <option value="南宁市">南宁市</option>
        </select>

        <label  for="houseType">类型:</label>
        <select style="position: relative;left: -60px" id="houseType" name="houseType">
            <option value="">全部</option>
            <option value="公寓">公寓</option>
            <option value="别墅">别墅</option>
        </select>

        <div><button style="width: 100px;position:relative;right:20px" onclick="searchProperties()">查询</button></div>
    </div>

    <div class="sort-options">
        <button onclick="sortProperties('default')" class="active">默认排序</button>
        <button onclick="sortProperties('priceAsc')">价格升序</button>
        <button onclick="sortProperties('priceDesc')">价格降序</button>
        <button onclick="sortProperties('areaAsc')">面积升序</button>
        <button onclick="sortProperties('areaDesc')">面积降序</button>
        <button onclick="sortProperties('timeDesc')">时间倒序</button>
    </div>

    <div id="property-list"></div>

    <div class="pagination">
        <button id="prev-page" onclick="loadData(currentPage - 1)">上一页</button>
        <button id="next-page" onclick="loadData(currentPage + 1)">下一页</button>
    </div>
</div>

<script>
    let currentPage = 1;
    const pageSize = 4;
    let currentSort = 'default'; // 默认排序方式

    document.addEventListener('DOMContentLoaded', function() {
        loadData(currentPage); // 初始加载数据
    });

    function getSearchParams() {
        const title = document.getElementById('title').value;
        const province = document.getElementById('province').value;
        const city = document.getElementById('city').value;
        const houseType = document.getElementById('houseType').value;
        return { title, province, city, houseType };
    }

    function buildUrl(page, params = {}) {
        const { title, province, city, houseType } = params;
        if(title==null&& province==null&& city==null&& houseType==null){
            return `http://localhost:8080/user/pageQueryNewProperty?page=${page}&pageSize=${pageSize}&type=1`;
        }
        let url = `http://localhost:8080/user/pageQueryLike?page=${page}&pageSize=${pageSize}&type=1`;

        if (title) url += `&title=${encodeURIComponent(title)}`;
        if (province) url += `&province=${encodeURIComponent(province)}`;
        if (city) url += `&city=${encodeURIComponent(city)}`;
        if (houseType) url += `&houseType=${encodeURIComponent(houseType)}`;
        return url;
    }

    function loadData(page, params = {}) {
        if (page < 1) return;

        const url = buildUrl(page, params);

        // Retrieve the token from localStorage
        const token = localStorage.getItem('token');

        // Check if the token is available
        if (!token) {
            console.error('No token found, please log in');
            return;
        }

        fetch(url, {
            method: 'GET',
            headers: {
                'Authorization': `Bearer ${token}`, // Include the token in the Authorization header
                'Content-Type': 'application/json'
            }
        })
            .then(response => response.json())
            .then(data => {
                if (data.code === 1) {
                    sortAndRenderData(data.data.rows);
                    currentPage = page;
                    updatePagination(data.data.total);
                } else {
                    console.error('Failed to load data:', data.msg);
                }
            })
            .catch(error => console.error('Error:', error));
    }

    function sortAndRenderData(data) {
        // 根据排序方式排序
        if (currentSort === 'priceAsc') {
            data.sort((a, b) => a.price - b.price);
        } else if (currentSort === 'priceDesc') {
            data.sort((a, b) => b.price - a.price);
        } else if (currentSort === 'areaAsc') {
            data.sort((a, b) => a.area - b.area);
        } else if (currentSort === 'areaDesc') {
            data.sort((a, b) => b.area - a.area);
        } else if (currentSort === 'timeDesc') {
            data.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
        }

        renderProperties(data);
    }

    function renderProperties(properties) {
        const propertyList = document.getElementById('property-list');
        propertyList.innerHTML = ''; // 清空旧数据

        properties.forEach(property => {
            const propertyDiv = document.createElement('div');
            console.log(property.propertyId);
            propertyDiv.className = 'property';
            propertyDiv.innerHTML = `
            <img style="width: 350px;height:200px;" src="${property.imageUrl}" alt="${property.title}">
            <div style="margin-left: 50px">
                <a href="details.html?propertyId=${property.propertyId}&price=${property.price}" style="text-decoration: none"  class="caption">${property.title}</a>

                <p>描述: ${property.description}</p>
                <p>位置: ${property.province} ${property.city} ${property.community}</p>
                <p>类型: ${property.houseType}</p>
                <p>面积: ${property.area} 平方米</p>
                <p>每平方: ${(property.price / property.area).toFixed(2)}万 元</p>
                <div class="price">￥${(property.price / 10000).toFixed(2)}<span style="font-size:18px;color:#cf1919;font-weight: lighter">万</span></div>
                <p style="position:relative;bottom:45px;">创建时间: ${new Date(property.createTime).toLocaleString()}</p>
            </div>
        `;
            propertyList.appendChild(propertyDiv);
        });
    }

    function updatePagination(totalItems) {
        const totalPages = Math.ceil(totalItems / pageSize);
        document.getElementById('prev-page').disabled = currentPage === 1;
        document.getElementById('next-page').disabled = currentPage >= totalPages;
    }

    function sortProperties(sortType) {
        currentSort = sortType;
        const params = getSearchParams();
        loadData(1, params); // 重新加载第一页数据以应用排序

        // 更新排序按钮的样式
        document.querySelectorAll('.sort-options button').forEach(button => {
            button.classList.remove('active');
        });
        document.querySelector(`[onclick="sortProperties('${sortType}')"]`).classList.add('active');
    }

    function searchProperties() {
        const params = getSearchParams();
        loadData(1, params); // 根据查询条件加载第一页数据
    }

</script>
</body>
</html>
